
use axum::{
    extract::{ Query, State}, http::{header::{HeaderMap, SET_COOKIE}, StatusCode}, response::{IntoResponse, Json, Redirect, Response}, Form };

use axum::response::Html;
use axum::response::Result as AResult;

use serde::{Deserialize, Serialize, *};
use std::sync::Arc;

use anyhow::{bail, Result};
use crate::*;
use chrono::prelude::*;
use common::{Config, Task, SearchParams};

type SharedHandle = Arc<Shared>;

pub async fn get_hello(State(shared): State<SharedHandle>, Query(q): Query<SearchParams>) ->  AResult<Response> {
   
    let s = Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
    logging::log!("get_hello: {:?}", s);
    let r = shared.dataset.read().unwrap();
    let count = r.len();

    return Ok( Html(format!(
             r#"<html><head><h1 align=center><Warnning</h1></head><body><BR><BR>
             <div align=center><span style="color:red">GET不建议在axum中实现，请把界面构成都交给leptos处理，以保证一致风格！</span></div>
             <BR>
             <div> Input is : {:?}</div>
             <BR>
             <div> dataset count = {}</div>
             </body>
             </html>"#,
            q, count
         )).into_response() )      
 }
 pub async fn post_todo(State(shared): State<SharedHandle>, Form(q): Form<SearchParams>, )  -> AResult<Response> {  
    /*
    let now = Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
    log::info!("{:?} insert into db, {:?}", q, &now);  

    let mut w = shared.dataset.write().unwrap();
    let mut t = Task { id: 0, name: q.query, timestamp: now , count:9};
    let count = w.len() as i32 + 1;
    t.id = count;
    (*w).push(t);
    drop(w);
    */
     
    let task = WorkTask::SendMessage(format!("hello, {}", q.query));
    if let Err(er) = shared
        .tx
        .send(task)
        .await{
            error!("{:?}", er);
        };
    
    return Ok(Redirect::to("/").into_response());
}
/// GET， /axum/get_task
/// @return Vec<Task>
pub async fn api_get_task(State(shared): State<SharedHandle>, Query(q): Query<SearchParams>) ->  AResult<Response> {
        
    let tasks = db::read_all_tasks(&shared.dbpool, 20).await.unwrap();
    logging::log!("[server api] api_get_task: count = {}", tasks.len());
    return Ok(Json(tasks).into_response())      
 }

 /// POST， /axum/post_task
 /// @return direct to /auxm page
 pub async fn api_post_task(State(shared): State<SharedHandle>, Form(q): Form<Task>, )  -> AResult<Response> {  
    let now = Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
    log::info!("{:?} insert into db, {:?}", q, &now);  
        
    let id = new_task(&shared.dbpool, &q.name, &now, q.count).await.unwrap();
    let next = format!("/axum?query={}", id);
    return Ok(Redirect::to(&next).into_response());
}
///////
pub async fn api_get_config(State(shared): State<SharedHandle>) ->  AResult<Response> {
    let cfg = shared.cfg.clone();
    return Ok(Json(cfg).into_response())      
}

